package ch.bfh.abcmmh.controller.operating.clock;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;

import javax.swing.Timer;

public class Clock extends Observable {

	private Timer timer;
	private int cycleCount;
	private int stopAtCycle = -1;

	public Clock(int delay_ms) {
		setCycles(0);
		this.timer = new Timer(delay_ms, new ObserverNotifier());
	}

	public Timer getTimer() {
		return timer;
	}

	private class ObserverNotifier implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			if (cycleCount == stopAtCycle)
				timer.stop();
			setCycles(getCycles() + 1);
			setChanged();
			notifyObservers();
			clearChanged();
		}
	}

	public void setStopAt(int cycle) {
		this.stopAtCycle = cycle;
	}

	private void setCycles(int cycles) {
		this.cycleCount = cycles;
	}

	public int getCycles() {
		return cycleCount;
	}

	public void setClockDelay(int delay) {
		if (delayIsAccepable(delay)) {
			timer.setDelay(delay);
		}
	}

	private boolean delayIsAccepable(int delay) {
		if (delay == 10 || delay == 50 || delay == 100 || delay == 300) {
			return true;
		}
		return false;
	}
}